package extend.db.transaction;

import extend.db.DbConnection;
import java.util.LinkedList;

/**
 * db 事务
 * <B>说明：</B>
 * <pre>
 *  略
 * </pre>
 * <B>示例：</B>
 * <pre>
 *  略
 * </pre>
 * <B>日志：</B>
 * <pre>
 *  略
 * </pre>
 * <B>注意事项：</B>
 * <pre>
 *  略
 * </pre>
 */
public class DbTransaction implements Transaction
{
    /**
     * 事务开启状态
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected boolean transOn = false;

    /**
     * 当前事务池连接列表
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected LinkedList<DbConnection>  dbConnections = new LinkedList<>();

    @Override
    public boolean beginTransaction()
    {
        this.commit();
        this.transOn = true;

        return true;
    }

    @Override
    public boolean commit()
    {
        boolean result = true;
        for (DbConnection dbConnection:dbConnections) {
            result = dbConnection.commit();
            if (result == false) {
                break;
            }
        }

        this.clearTrans();

        return result;
    }

    @Override
    public boolean rollback()
    {
        boolean result = true;
        for (DbConnection dbConnection:dbConnections) {
            result = dbConnection.rollback();
            if (result == false) {
                break;
            }
        }

        this.clearTrans();

        return result;
    }

    @Override
    public boolean clearTrans()
    {
        this.transOn = false;
        this.dbConnections.clear();
        return false;
    }

    @Override
    public void addTransDb(String dbConnKey, DbConnection dbConnection)
    {
        this.dbConnections.add(dbConnection);
    }
}
